package io.mybatis.provider.defaults;

import cn.virens.common.exception.APIException;
import io.mybatis.provider.EntityTable;
import io.mybatis.provider.EntityTableFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 覆盖：支持缓存实体类信息的方法
 *
 * @author virens
 */
public class CachingEntityTableFactory implements EntityTableFactory {
    private final Map<Class<?>, EntityTable> ENTITY_CLASS_MAP = new ConcurrentHashMap<>();

    @Override
    public EntityTable createEntityTable(Class<?> entityClass, Chain chain) {
        if (ENTITY_CLASS_MAP.get(entityClass) == null) {
            synchronized (entityClass) {
                if (ENTITY_CLASS_MAP.get(entityClass) == null) {
                    EntityTable entityTable = chain.createEntityTable(entityClass);
                    if (entityTable != null) {
                        ENTITY_CLASS_MAP.put(entityClass, entityTable);
                    } else {
                        return null;
                    }
                }
            }
        }
        return ENTITY_CLASS_MAP.get(entityClass);
    }

    @Override
    public int getOrder() throws APIException {
        return Integer.MAX_VALUE - 100;
    }
}
